package com.mdd.front.service.impl;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.pay.IPayService;
import com.mdd.front.service.order.IOrderService;
import com.mdd.front.service.pay.IBalancePayService;
import com.mdd.front.service.pay.IWxpayService;
import com.mdd.front.service.recharge.IRechargeService;
import com.mdd.front.validate.BalancePayValidate;
import com.mdd.front.validate.PaymentValidate;
import com.mdd.front.vo.wxpay.WxPayCreateOrderRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

@Service
public class PayServiceImpl implements IPayService {
    @Resource
    private IWxpayService iWxpayService;
    @Resource
    private IBalancePayService iBalancePayService;

    @Resource
    private IOrderService iOrderService;
    @Resource
    private IRechargeService iRechargeService;

    @Override
    public Object prePay(PaymentValidate paymentValidate) throws WxPayException {

        // 更新支付方式
        switch (paymentValidate.getScene()){
            case "order":
                iOrderService.updateOrderPayWay(paymentValidate.getOrderId(), paymentValidate.getPayWay());
                break;
            case "recharge":
                iRechargeService.updateRechargePayWay(paymentValidate.getOrderId(), paymentValidate.getPayWay());
                break;
        }

        // 组装支付参数
        WxPayCreateOrderRequest request = new WxPayCreateOrderRequest();
        request.setOrderId(paymentValidate.getOrderId());
        request.setPayChannel(paymentValidate.getPayChannel());
        switch (paymentValidate.getPayWay()){
            case 1:
                if("order".equals(paymentValidate.getScene())){
                   return iWxpayService.createOrder(request);
                }
                if ("recharge".equals(paymentValidate.getScene())){
                    return iWxpayService.createOrder(request);
                }
            case 2:
                if ("order".equals(paymentValidate.getScene())){
                    BalancePayValidate balancePayValidate = new BalancePayValidate();
                    balancePayValidate.setOrderId(paymentValidate.getOrderId());
                    iBalancePayService.balance2PayOrder(balancePayValidate, LikeFrontThreadLocal.getUserId());
                    return "支付成功！";
                }
                Assert.isTrue(!"recharge".equals(paymentValidate.getScene()),"充值订单不支持余额支付！");
        }
        return "支付失败";
    }
}
